import { useUserStore } from '@/store/user'
import axios from 'axios'
import { ElNotification } from 'element-plus'
import router from '@/router'

const http = axios.create({
    baseURL: '/api',
})

// 先创建 store 实例，避免每次拦截器都重新调用
const store = useUserStore()

// 请求拦截器
http.interceptors.request.use(
    (config) => {
        if (store.userInfo.tokenValue) {
            config.headers['token'] = store.userInfo.tokenValue
        }
        return config
    },
    (error) => {
        return Promise.reject(error)
    },
)

// 响应拦截器
http.interceptors.response.use(
    (response) => {
        if (response.data.code !== 200 && response.data.code !== 0) {
            if (response.data.msg) {
                ElNotification.error({ title: '错误', message: response.data.msg });
            }
            if (response.data.code === 402) {
                store.setUserInfo({});
                setTimeout(() => {
                    router.push('/login');
                }, 0);
            }
            return Promise.reject(response.data);
        }
        return response.data;
    },
    (error) => {
        ElNotification.error({ title: '请求失败', message: error.message || '未知错误' });
        return Promise.reject(error);
    }
);

export default http
